import React, { Component } from "react";
import { CSSTransition } from "react-transition-group";
import ReactDOM from "react-dom";

import "./index.css";

export interface IProps {
  title?: string;
  visible: boolean;
  onCancel: () => void;
  onOk?: () => void;
  container?: HTMLDivElement | undefined;
}

export interface IState {
  visible: boolean;
}

let container: HTMLDivElement | undefined;

export default class Modal extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      visible: false,
    };
    container = props.container;
  }

  static getDerivedStateFromProps(props: any, state: any) {
    if (props.visible !== state.visible) {
      return { visible: props.visible };
    }
    return null;
  }

  closeModal() {
    const { onCancel } = this.props;
    onCancel && onCancel();
  }

  confirm() {
    const { onOk } = this.props;
    onOk && onOk();
  }

  maskClick() {
    this.closeModal();
  }

  render() {
    const { visible } = this.state;

    if (!container) {
      container = document.createElement("div");
      document.body.appendChild(container);
    }

    const { title, children } = this.props;
    return ReactDOM.createPortal(
      <>
        <CSSTransition
          in={visible}
          classNames="courtyard-alert"
          timeout={300}
          unmountOnExit
        >
          <div className="courtyard-modal">
            <div className="courtyard-modal-title">{title}</div>
            <div className="courtyard-modal-content">{children}</div>
            <div className="courtyard-modal-operator">
              <button
                onClick={this.closeModal.bind(this)}
                className="courtyard-modal-operator-close"
              >
                取消
              </button>
              <button
                onClick={this.confirm.bind(this)}
                className="courtyard-modal-operator-confirm"
              >
                确认
              </button>
            </div>
          </div>
        </CSSTransition>
        <CSSTransition
          in={visible}
          classNames="courtyard-mask"
          timeout={300}
          unmountOnExit
        >
          <div
            className="courtyard-mask"
            onClick={this.maskClick.bind(this)}
          ></div>
        </CSSTransition>
      </>,
      container
    );
  }
}
